package com.support.mvc.encrypt.convert;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.support.mvc.encrypt.AesApiId;
import com.utils.enums.Code;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;
import java.util.Objects;

/**
 * 用于 JSON 序列化和反序列化， @JSONField(serializeUsing = AesApiIdStringJsonConvert.Serializer.class, deserializeUsing = AesApiIdStringJsonConvert.Deserializer.class)
 *
 * @author 谢长春 2022-02-06
 */
@Slf4j
public class AesApiIdStringJsonConvert {

//    public static class Serializer implements ObjectSerializer {
//
//        @Override
//        public void write(JSONSerializer serializer, Object value, Object fieldName, Type fieldType, int features) throws IOException {
//            if (Objects.isNull(value)) {
//                return;
//            }
//            if (log.isDebugEnabled()) {
//                log.debug("加密:{}:{}", fieldName, value);
//            }
//            serializer.write(AesApi.encrypt(Objects.toString(value)));
//        }
//    }
//
//    public static class Deserializer implements ObjectDeserializer {
//        @SuppressWarnings({"unchecked"})
//        @Override
//        public <T> T deserialze(DefaultJSONParser defaultJSONParser, Type fieldType, Object fieldName) {
//            final String value = defaultJSONParser.parseObject(String.class);
//            if (Objects.isNull(value)) {
//                return null;
//            }
//            if (log.isDebugEnabled()) {
//                log.debug("解密:{}:{}", fieldName, value);
//            }
//            try {
//                final Object val = AesApi.decrypt(value);
//                return (T) val;
//            } catch (Exception e) {
//                throw Code.A00003.toCodeException(value, e);
//            }
//        }
//
//        @Override
//        public int getFastMatchToken() {
//            return JSONToken.LITERAL_STRING;
//        }
//    }

    /**
     * id 反序列化， 去掉携带的 updateTime
     */
    public static class AesIdDeserializer implements ObjectDeserializer {
        @SuppressWarnings({"unchecked"})
        @Override
        public <T> T deserialze(DefaultJSONParser defaultJSONParser, Type fieldType, Object fieldName) {
            final String value = defaultJSONParser.parseObject(String.class);
            if (Objects.isNull(value)) {
                return null;
            }
            if (log.isDebugEnabled()) {
                log.debug("解密:{}:{}", fieldName, value);
            }
            try {
                return (T) AesApiId.decrypt(value).getStringId(); // 去掉携带的 updateTime;
            } catch (Exception e) {
                throw Code.A00003.toCodeException(value, e);
            }
        }

        @Override
        public int getFastMatchToken() {
            return JSONToken.LITERAL_STRING;
        }
    }


}
